using System;
using AzureContrib.WindowsAzure.Diagnostics;
using AzureContrib.WindowsAzure.Properties;

namespace AzureContrib.WindowsAzure.ServiceRuntime
{
	/// <summary>
	/// Access to configuration settings
	/// </summary>
	public static class IRoleEnvironmentExtensions
	{
		/// <summary>
		/// <see cref="IRoleEnvironment.GetConfigurationSettingValue"/>
		/// </summary>
		public static string GetConfigurationSetting(this IRoleEnvironment roleEnvironment, string roleSettingName)
		{
			string configurationSetting = roleEnvironment.GetConfigurationSettingValue(roleSettingName);

			if (configurationSetting == null)
			{
				throw new ArgumentException(string.Format(Strings.CouldNotFindAppSetting, roleSettingName));
			}

			return configurationSetting;
		}

		/// <summary>
		/// <see cref="IRoleEnvironment.GetConfigurationSettingValue"/>
		/// </summary>
		public static bool GetBoolConfigurationSetting(this IRoleEnvironment roleEnvironment, string roleSettingName, ITrace trace)
		{
			try
			{
				return bool.Parse(GetConfigurationSetting(roleEnvironment, roleSettingName));
			}
			catch (FormatException exception)
			{
				trace.Error(Strings.CouldNotParseKey, "bool", roleSettingName, exception.Message);
				throw;
			}
		}

		/// <summary>
		/// <see cref="IRoleEnvironment.GetConfigurationSettingValue"/>
		/// </summary>
		public static bool TryGetBoolConfigurationSetting(this IRoleEnvironment roleEnvironment, string roleSettingName, ITrace trace, out bool value)
		{
			try
			{
				string settingValue;
				if (roleEnvironment.TryGetConfigurationSettingValue(roleSettingName, out settingValue))
				{
					value = bool.Parse(settingValue);
					return true;
				}
			}
			catch (FormatException exception)
			{
				trace.Error(Strings.CouldNotParseKey, "bool", roleSettingName, exception.Message);
			}

			value = false;
			return false;
		}

		/// <summary>
		/// <see cref="IRoleEnvironment.GetConfigurationSettingValue"/>
		/// </summary>
		public static int GetIntConfigurationSetting(this IRoleEnvironment roleEnvironment, string roleSettingName, ITrace trace)
		{
			try
			{
				return int.Parse(GetConfigurationSetting(roleEnvironment, roleSettingName));
			}
			catch (FormatException exception)
			{
				trace.Error(Strings.CouldNotParseKey, "int", roleSettingName, exception.Message);
				throw;
			}
		}
	}
}